package cn.lastcc.pwdmanage.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;

/**
 * 序列化相关工具，主要用于存取数据文件，作为本程序的持久化工具
 *
 * @author Added by baidongyang 2013-6-23
 *
 */
public class SerialUtil {

    private static Info _info;

    private static void createFile (File file) throws FileNotFoundException {
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }
    }

    public static Info getInfo() throws IOException, ClassNotFoundException {
        if (null == _info) {
            File file = new File(IConstant.INFO_FILE_PATH);
            createFile(file);
            if (!file.isDirectory()) {
                if (!file.delete()) {
                    throw new IOException(IConstant.INFO_FILE_PATH_NAME + " is invald data file.");
                }
                createFile(file);
            }
            // 进行反序列化
            ObjectInputStream in = null;
            Object obj = null;
            try {
                in = new ObjectInputStream(new FileInputStream(IConstant.INFO_FILE_PATH_NAME));
                obj = in.readObject();
            } catch (IOException e) {
                throw e;
            } finally {
                if (null != in) {
                    in.close();
                }
            }
            if (obj instanceof Info) {
                _info = (Info) obj;
            } else {
                throw new InvalidObjectException("文件解析失败");
            }
        }
        return _info;
    }

    public static void setInfo(Info info) throws FileNotFoundException, IOException {
        _info = info;
        File infoFile = new File(IConstant.INFO_FILE_PATH_NAME);
        // 删除已序列化的文件
        if (null == info) {
            infoFile.delete();
        }
        // 序列化文件保存数据
        else {
            // 如果父目录不存在则创建
            if (!infoFile.getParentFile().exists()) {
                infoFile.getParentFile().mkdirs();
            }
//            if (infoFile.exists()) {
//                infoFile.delete();
//            }
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(infoFile));
            out.writeObject(info);
            out.flush();
            out.close();
        }
    }
}
